package ca.uwo.android.rss.events;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParserException;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import ca.uwo.android.R;
import ca.uwo.android.mustangs.MustangsScheduleParser;
import ca.uwo.android.rss.RssFeed;
import ca.uwo.android.rss.RssItem;
import ca.uwo.android.rss.SaxEventCalendarParser;
import ca.uwo.android.rss.SaxRssParser;
import ca.uwo.android.rss.events.RssEventsFeed.GridCellAdapter;
import ca.uwo.android.rss.events.RssEventsFeed.ListAdapter;
import ca.uwo.android.sslconnection.WesternHttpClient;
import ca.uwo.android.rss.events.EventsDataSource;
import ca.uwo.android.rss.events.RssEvent;
import ca.uwo.android.rss.events.StackOverflowXmlParser;

import android.app.Activity;  
import android.app.ProgressDialog;  
import android.os.AsyncTask;  
import android.os.Bundle;  
import android.preference.PreferenceManager;

public class RssEventsFeed extends Activity implements OnClickListener {
	
	private static final String tag = "Main";
	//private TextView selectedDayMonthYearButton;
	//private TextView currentMonth;
	private TextView monthTitle;		//Title given in the calendar between the previous and next month arrows
	private Button selectedDay;			
	private ImageView settingsButton;		//The button at the bottom of the app to change the RSS feed settings
	private ImageView monthButton;			//the button to change to month view
	private ImageView listButton;			//the button to change to list view
	private ImageView prevMonth;		//the arrow to get to previous month
	private ImageView nextMonth;		//the arrow to get to next month
	private GridView calendarView;		//the calendar view to hold the dates
	private GridCellAdapter gridAdapter;	//the adapter to plug in the calendar data
	private ListView eventListView;			//the list view to hold the events in the month view
	private ListView eventListView2;		//the list view to hold events in the List view
	private ListAdapter listAdapter;		//the adapter to plug in the events
	private ListAdapter expandablelistAdapter;
	private Calendar _calendar;				//the calendar object for month view
	private int month, year;				//the current month and year
	private final DateFormat dateFormatter = new DateFormat();
	private final String dateTemplate = "MMMM yyyy";
	/**
	 * Used to tag log messages from this class
	 */
	private static final String TAG_NAME = "RssEventsFeed";
	
	/** 
	 * A list button added to the top of the calendar
	 * Needed for developing the expandable list view
	 */
	
	/**
	 * constants to determine which type of dates feed is to be parsed
	 */
	public static final int EVENTSCALENDAR = 0;
	public static final int SESSIONALDATES = 1;
	public static final int SERVICEINTERRUPTIONS = 2;
	public static final int ALUMNIEVENTS = 3;
	public static final int MUSTANGSCHEDULE = 4;
	
	
	public static final int MONTH = 0;
	public static final int LIST = 1;
	

	/**
	 * url of the clicked feed item
	 */
	private String url="hi";

	/**
	 * set as one of the above constants
	 */
	private int feedType;

	/**
	 * The title to show in the module header
	 */
	private String datesFeedHeader;

	/**
	 * stores the rss feed of the url
	 */
	private List<RssEvent> fullRssFeed;

	/**
	 * The currently-displayed rss feed
	 */
	private RssFeed displayedRssFeed;

	/**
	 * stores the events / deadlines
	 */
	private Vector<Vector<String>> displayedEvents;

	/**
	 * Handle configuration changes ourselves. Implementing this method and
	 * adding android:configChanges="keyboardHidden|orientation" to the manifest
	 * for this activity means that the onCreate method will not be called every
	 * time a user rotates their phone.
	 */
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private ProgressDialog progressDialog; 

	
	
	private String ACADEMIC_URL;
	private String ALUMNI_URL;
	private String MUSTANGS_URL;
	private String SERVICE_URL;
	private String WESTERN_URL;
	
	private final String [] URL_names = {"Academic", "Alumni", "Mustangs", "Service", "Western"};
	private WesternHttpClient httpClient;
	private EventsDataSource datasource;


	@Override
	/**
	 * onCreate
	 * Gets the intent information and executes the async task that creates a loading bar, parses the rssfeeds and loads the interface*/
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		
		ACADEMIC_URL = getIntent().getExtras().getString("ACADEMIC_URL");
		ALUMNI_URL = getIntent().getExtras().getString("ALUMNI_URL");
		MUSTANGS_URL = getIntent().getExtras().getString("MUSTANGS_URL");
		SERVICE_URL = getIntent().getExtras().getString("SERVICE_URL");
		WESTERN_URL = getIntent().getExtras().getString("WESTERN_URL");

		new LoadViewTask().execute();   
	}
	

// =======
		/**
		 * AsyncTask Class
		 * Needed to execute threaded tasks for loading screen
		 * */
	    private class LoadViewTask extends AsyncTask<Void, Integer, Void> {
	    	   
	        /**
	         * Create loading bar before running parsing code in separate thread  
	         * 
	         * */
	        @Override  
	        protected void onPreExecute() {  
	        	
	            //Create a new progress dialog  
	            progressDialog = new ProgressDialog(RssEventsFeed.this);  
	            //Set the progress dialog to display a horizontal progress bar  
	            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
	            //Set the dialog title to 'Loading...'  
	            progressDialog.setTitle("Loading...");  
	            //Set the dialog message to 'Loading application View, please wait...'  
	            progressDialog.setMessage("Loading application View, please wait...");  
	            //This dialog can't be canceled by pressing the back key  
	            progressDialog.setCancelable(false);  
	            //This dialog isn't indeterminate  
	            progressDialog.setIndeterminate(false);  
	            //The maximum number of items is 100  
	            progressDialog.setMax(100);  
	            //Set the current progress to zero  
	            progressDialog.setProgress(0);  
	            //Display the progress dialog  
	            
	            progressDialog.show();  
	        }  
	  
	        /**
	         * 
	         * Parse the Rss Feeds in the background  */
	        @Override  
	        protected Void doInBackground(Void... params) {  
        		
	        	datasource = new EventsDataSource(RssEventsFeed.this);
	            datasource.open_database();
                boolean entries_exist = datasource.hasEntries();	
                publishProgress(25);  
                if(entries_exist == false){
                 	Log.i("BEN", "*********************** NO DATABASE ENTRIES DETECTED");
                	try {
						fullRssFeed = loadXmlFromNetwork(datasource);
						publishProgress(75);  
					} catch (IOException e) {
		                Log.i("ERROR", "" + getResources().getString(R.string.connection_error));
		                fullRssFeed = null;
		            } catch (XmlPullParserException e2) {
		            	Log.e("Error Parsing Xml", e2.getCause() + " lll " + e2.getStackTrace() + " lll " + e2.getMessage());
		                getResources().getString(R.string.xml_error);
		                fullRssFeed = null;
		            } catch (Exception e) {
						e.printStackTrace();
						fullRssFeed = null;
					}  
                }
                else{
                   	Log.i("BEN", "*********************** DATABASE ENTRIES EXIST");
                   	fullRssFeed = datasource.getAllEntries();
                   	publishProgress(75);  
                }   
                publishProgress(100);
				return null;
	        }
		
	  
	        /**
	         * After executing the Rssfeed parsing, load the interface 
	         */
	        @Override  
	        protected void onPostExecute(Void result)  
	        {  
	            //close the progress dialog  
	            progressDialog.dismiss();  
	            //initialize the View  
	          //initialize the View  
	            initializeMonthView();  
	        }    
	                  
	         
	    
	        //Update the progress  
	        @Override  
	        protected void onProgressUpdate(Integer... values)  
	        {  
	            //set the current progress of the progress dialog  
	            progressDialog.setProgress(values[0]);  
	        }  
	        
    }
		    	

    private List<RssEvent> loadXmlFromNetwork(EventsDataSource datasource) throws Exception {
    	
    	Log.i("BEN", "TESTING1");
    	
        InputStream stream = null;
        StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();  
                          
        String[] URL = {ACADEMIC_URL, ALUMNI_URL, MUSTANGS_URL, SERVICE_URL, WESTERN_URL};
        
        List<RssEvent> entries = new ArrayList<RssEvent>();
        
        Log.i("BEN", "TESTING2");
        
        for(int i = 0; i < 5; i++){
        	
        	Log.i("TIME111111", "TIME: " + Calendar.getInstance().getTime().toString());
        //	datasource.createFeed(URL[i], URL_names[i], Calendar.getInstance().getTime().toString());
        	
        	try {
        		
        	    Log.i("BEN", "TESTING3");
        		stream = getInputStream(URL[i]);
        		Log.i("TESTING", "STREAM: " + URL_names[i]);
        		entries.addAll(stackOverflowXmlParser.parse(stream, i+1, datasource));
         	
        		// Makes sure that the InputStream is closed after the app is
        		// finished using it.
            } 
        	finally {
        		if (stream != null) 
        			stream.close();
            }  	
        } // end for
        
        Log.i("BEN", "TESTING4");
        return entries;
      } // end method   
		        
        
    	/**
    	 * This method is used to open a connection to the rss feed and return an
    	 * input stream to it for reading / parsing
    	 * 
    	 * @return InputStream input stream from rss feed
    	 */
    	protected InputStream getInputStream(String urlString) throws Exception {
    		URL rssFeedURL = new URL(urlString);
    		if (!rssFeedURL.getProtocol().equals("https")) {
    			Log.i("HTPP_INFO", "http getting executed");
    			return rssFeedURL.openConnection().getInputStream();
    		} else {
    			Log.i("HTPPS_INFO", "https getting executed");
    			return getInputStreamFromHTTPS(rssFeedURL);
    		}
    	}

    	/**
    	 * 
    	 * @return returns InputStream from rss feed
    	 * @throws Exception
    	 *             Exception to be thrown
    	 */
    	protected InputStream getInputStreamFromHTTPS(URL feedURL) throws Exception {
    		try {
    			this.httpClient = new WesternHttpClient(this);
    			HttpGet httpGet = new HttpGet(feedURL.toExternalForm());
    			httpGet.setHeader("Accept", "text/plain");
    			HttpResponse httpResponse = httpClient.execute(httpGet);
    			HttpEntity entity = httpResponse.getEntity();
    			int lastResponseCode = httpResponse.getStatusLine().getStatusCode();
    			if (lastResponseCode == 400) {
    				throw new Exception("NOT FOUND: " + httpResponse.getStatusLine());
    			} else if (lastResponseCode == 500) {
    				throw new Exception("Internal server error:  "
    						+ httpResponse.getStatusLine());
    			}
    			InputStream input = entity.getContent();
    			return input;

    		} catch (IOException ex) {
    			ex.printStackTrace();
    			throw new Exception("Connection Error, Please Try Again Later");
    		}
    	}
		        
		        
    	
	public void initializeMonthView(){
		
		
		/* 
		 * 
		 * NEW LIST IS NOW HERE! 
		 *  
		 */
		
		
		
		setContentView(R.layout.event_month_view);
		 datesFeedHeader = getIntent().getExtras().getString("HEADER");
 		
 		((TextView) findViewById(R.id.moduleName)).setText(datesFeedHeader);
		
		_calendar = Calendar.getInstance(Locale.getDefault());
		
		month = _calendar.get(Calendar.MONTH);
		year = _calendar.get(Calendar.YEAR);
		
		Log.d("Initialize Month View","month is:"+month);
		Log.d("Initialize Month View","year is:"+year);
		settingsButton = (ImageView) this.findViewById(R.id.settings_button);
		
		settingsButton.setOnClickListener(this);
		
		listButton = (ImageView) this.findViewById(R.id.list_button);
		
		listButton.setOnClickListener(this);
		
		monthButton = (ImageView) this.findViewById(R.id.month_button);
	
		monthButton.setOnClickListener(this);

		prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
		prevMonth.setOnClickListener(this);

		//currentMonth = (TextView) this.findViewById(R.id.currentMonth);
		//currentMonth.setText("Current Month:"+_calendar.getTime().toString());

		nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
		nextMonth.setOnClickListener(this);

		monthTitle = (TextView) this.findViewById(R.id.monthTitle);
		monthTitle.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
		
		calendarView = (GridView) this.findViewById(R.id.calendar);
		eventListView = (ListView) this.findViewById(R.id.eventList);
		

		// Initialised
		gridAdapter = new GridCellAdapter(getApplicationContext(), R.id.day_gridcell, month, year);
		gridAdapter.notifyDataSetChanged();
		calendarView.setAdapter(gridAdapter);
		
		
		
		if (this.fullRssFeed == null){
			
			Log.d("Jennifer","RssFeed is null");
		}
		
		// Initialised
		Date calendarDate = new GregorianCalendar(year,month,_calendar.get(Calendar.DAY_OF_MONTH)).getTime();
		
		Log.d("Jennifer","CalendarDate in init: "+calendarDate.toString());
		listAdapter = new ListAdapter(getApplicationContext(), R.id.list_item,this.fullRssFeed,calendarDate );
		listAdapter.notifyDataSetChanged();
		eventListView.setAdapter(listAdapter);
		
	}
	
	public void initializeListView(){
		 datesFeedHeader = getIntent().getExtras().getString("HEADER");
 		
 		((TextView) findViewById(R.id.moduleName)).setText(datesFeedHeader);
		setContentView(R.layout.event_list_view);
		
		
		settingsButton = (ImageView) this.findViewById(R.id.settings_button);
		
		settingsButton.setOnClickListener(this);
		
		listButton = (ImageView) this.findViewById(R.id.list_button);
		
		listButton.setOnClickListener(this);
		
		monthButton = (ImageView) this.findViewById(R.id.month_button);
		
		monthButton.setOnClickListener(this);

		eventListView2 = (ListView) this.findViewById(R.id.listViewList);
	
		// Initialised
		
		expandablelistAdapter = new ListAdapter(getApplicationContext(), R.id.list_item,fullRssFeed);
		expandablelistAdapter.notifyDataSetChanged();
		eventListView2.setAdapter(expandablelistAdapter);
		
	}
	

	
	@Override
	public void onClick(View v)
		{
			/** 
			 * A list button added to the top of the calendar
			 * Needed for developing the expandable list view
			 */
	        /*if (v.equals(expandableListBtn)) {
	        	Intent intent = new Intent(this, ca.uwo.android.rss.events.RssDatesFeed.class);
	    		intent.putExtra("URL", getString(R.string.western_events_feed));
    			intent.putExtra("HEADER", getString(R.string.westernevents_title));
    			intent.putExtra("TYPE", RssDatesFeed.EVENTSCALENDAR);
    			startActivity(intent); 
	        }*/
		
			if (v==settingsButton){
				setContentView(R.layout.event_settings_view);
			}
			if (v==listButton){
				/*Intent intent = new Intent(this, ca.uwo.android.rss.events.RssDatesFeed.class);
	    		intent.putExtra("URL", getString(R.string.western_events_feed));
    			intent.putExtra("HEADER", getString(R.string.westernevents_title));
    			intent.putExtra("TYPE", RssDatesFeed.EVENTSCALENDAR);
    			startActivity(intent); */
				initializeListView();
			}
			if (v==monthButton){
				initializeMonthView();
			}
			if (v == prevMonth)
				{
				Log.d("Jennifer","Previous month starts as:"+month);
					if (month <= 0)
						{
							month = 11;
							year--;
						} else
						{
							month--; 
						}
					
					Log.d("Jennifer","Previous month ends as:"+month);
					gridAdapter = new GridCellAdapter(getApplicationContext(), R.id.day_gridcell, month, year);
					int day=1;
					if(month==1 &&_calendar.get(Calendar.DAY_OF_MONTH)>28){
						day=28;
					}
					else if ((month==3||month==5||month==8||month==10)&&_calendar.get(Calendar.DAY_OF_MONTH)>30){
						day=30;
					}
					else{
						day=_calendar.get(Calendar.DAY_OF_MONTH);
					}
					
					
					Log.d("Check Next/Prev Month","year and month:"+year+" "+month);
					
					_calendar.set(year, month, day);
					//currentMonth.setText("Current Month: "+_calendar.getTime().toString());
					Log.d("Jennifer",(String) dateFormatter.format(dateTemplate, _calendar.getTime()));
					monthTitle.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
					gridAdapter.notifyDataSetChanged();
					calendarView.setAdapter(gridAdapter);
				}
			if (v == nextMonth)
				{
					if (month >= 11)
						{
							month = 0;
							year++;
						} else
						{
							month++;
						}

					gridAdapter = new GridCellAdapter(getApplicationContext(), R.id.day_gridcell, month, year);
					int day;
					if(month==1 &&_calendar.get(Calendar.DAY_OF_MONTH)>28){
						day=28;
					}
					else if ((month==3||month==5||month==8||month==10)&&_calendar.get(Calendar.DAY_OF_MONTH)>30){
						day=30;
					}
					else{
						day=_calendar.get(Calendar.DAY_OF_MONTH);
					}
					
					Log.d("Check Next/Prev Month","year and month:"+year+" "+month);
					_calendar.set(year, month, day);
					//currentMonth.setText("Current Month: "+_calendar.getTime().toString());
					monthTitle.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
					gridAdapter.notifyDataSetChanged();
					calendarView.setAdapter(gridAdapter);
				}
		}

	public String[] getDates(List<RssEvent> rssFeed) {

		Vector<String> dates = new Vector<String>();
		int eventTotal = 1;
		int maxEvents = 0;
		String thisDate = null;

		for (RssEvent item : rssFeed) {

			thisDate = item.getDate();

			if (dates.size() == 0 || !dates.lastElement().equals(thisDate)) {
				eventTotal = 0;
				dates.add(thisDate);
			}

			eventTotal++;
			if (eventTotal > maxEvents) {
				maxEvents = eventTotal;
			}

		}
		
		return dates.toArray(new String[dates.size()]);
	}
	
	
	
	
	
	public class ListAdapter extends BaseAdapter implements OnClickListener
	{
		private final Context _context;
		private Vector<RssEvent> eventItems;
		private TextView listItem;
		private Date calendarDate;
		
		public ListAdapter(Context context, int textViewResourceId,List<RssEvent>rssFeed, Date cDate)
		{
			super();
			
			this._context = context;
			this.eventItems = new Vector<RssEvent>();
			Log.d("Jennifer","Calendar Date on Entry: "+cDate.toString());
			this.calendarDate = cDate;
			//TODO add an error dialog
			if(rssFeed == null)
				Log.d(TAG_NAME,"RSS FEED IS NULL");

			// store unique dates in string
			// array
			
			String[] dates = getDates(rssFeed);
			//Log.i("Jennifer", "Dates in displayRssFeed are:  " + dates);
			//Log.i("Jennifer", "Size of RssFeed is :  " + rssFeed.size());

			// store events for each date in a 2D vector of Strings
			Vector<Vector<String>> events = new Vector<Vector<String>>(dates.length);
			Vector<String> eventsList = new Vector<String>();
			events.add(eventsList);

			Date currentDate=null;

			boolean continueLoop = true;
			int i = 0;
			
			Log.d("Jennifer RssEvents","Test at 0:"+rssFeed.get(i).getDate());
			
			
			while (continueLoop==true) {

				RssEvent item = rssFeed.get(i);					//get the rss Item	
				
				try{
						
					currentDate = item.getDateObject();				//get the date from the item
					//Log.d("Jennifer","CurrentDate: "+currentDate.toString());
					//Log.d("Jennifer","Current Date String: "+item.getDate().toString());
					//Log.d("Jennifer","CalendarDate: "+this.calendarDate.toString());
					if(currentDate.compareTo(calendarDate)==0){		//dates are the same add the item
						eventItems.add(item);
					}
					else if(currentDate.compareTo(calendarDate)>0){
						continueLoop=false;
					}
					
				}
				catch(Exception e){
					
					Log.d("Jennifer","There was an error:"+e);
				}
				if(i>=rssFeed.size()-1){
					
					continueLoop=false;
				}
				i++;
			}
			
		}
		
		public ListAdapter(Context context, int textViewResourceId,List<RssEvent> rssFeed)
		{
			super();
						
			this._context = context;
			this.eventItems = new Vector<RssEvent>();
		
			//TODO remove this as it is a temp fix
			if(rssFeed == null)
				Log.d(TAG_NAME,"RssFeed is NULL - add dialog box");

	

			boolean continueLoop = true;
			String currentDateString = null;

			for (int i = 0; i < rssFeed.size(); i++) {

				RssEvent item = rssFeed.get(i);

				if (currentDateString == null)
					currentDateString = item.getDate();

				// if it is a unique date from previous one, add it to list
				if (currentDateString.compareTo(item.getDate()) != 0) {
					eventItems.add(item);
				}
				
			}
			
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return eventItems.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View row = convertView;
			if (row == null)
				{
					// ROW INFLATION
					Log.d(tag, "Starting XML Row Inflation ... ");
					LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					row = inflater.inflate(R.layout.calendar_list_item, parent, false);

					Log.d(tag, "Successfully completed XML Row Inflation!");
				}

			// Get a reference to the Day gridcell
			listItem = (TextView) row.findViewById(R.id.list_item);
			listItem.setTag(eventItems.get(position));
			listItem.setOnClickListener(this);
			
			listItem.setText(eventItems.get(position).getTitle());
			
			return row;
		}

		@Override
		/**
		 * OnClick for individual list item
		 * 
		 * */
		public void onClick(View view) {
			Intent showSummary = null;
			RssEvent clickedItem = (RssEvent)view.getTag();
			// TODO Auto-generated method stub
			if (feedType == MUSTANGSCHEDULE) {
				
				showSummary = new Intent(RssEventsFeed.this,
						ca.uwo.android.mustangs.MustangsDateItemSummary.class);

				// pass the information required to populate fields in
				// summary
				// screen
				showSummary.putExtra("DATE", clickedItem.getDate());
				showSummary.putExtra("TITLE", clickedItem.getTitle());
				showSummary.putExtra("RESULTS", clickedItem
						.getDescription());
				showSummary.putExtra("LINK", clickedItem
						.getLink());
				showSummary.putExtra("TYPE", feedType);
			} else {
				showSummary = new Intent(RssEventsFeed.this,
						ca.uwo.android.rss.events.DateItemSummary.class);

				// pass the information required to populate fields in
				// summary
				// screen
				showSummary.putExtra("DATE", clickedItem.getDate());
				showSummary.putExtra("TITLE", clickedItem.getTitle());
				showSummary.putExtra("SUMMARY", clickedItem
						.getDescription());
				showSummary.putExtra("TYPE", feedType);

			}
			startActivity(showSummary); // display the summary screen to the
			// user
		
			
		}
		
	}
	
	
	
	// Inner Class
	public class GridCellAdapter extends BaseAdapter implements OnClickListener
		{
			private static final String tag = "GridCellAdapter";
			private final Context _context;
			private final List<String> list;
			private final String[] weekdays = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
			private final String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
			private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
			private final int month, year;
			int daysInMonth, prevMonthDays;
			private final int currentDayOfMonth;
			private Button gridcell;

			// Days in Current Month
			public GridCellAdapter(Context context, int textViewResourceId, int month, int year)
				{
					super();
					this._context = context;
					this.list = new ArrayList<String>();
					this.month = month;
					this.year = year;

					
					Calendar calendar = Calendar.getInstance();
					currentDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
					
					//Log.d("Jennifer "+tag, "Month: " + month + " " + "Year: " + year + " Day: "+ currentDayOfMonth);

					printMonth(month, year);
				}

			public String getItem(int position)
				{
					return list.get(position);
				}

			@Override
			public int getCount()
				{
					return list.size();
				}

			private void printMonth(int mm, int yy)
				{
					// The number of days to leave blank at
					// the start of this month.
					int trailingSpaces = 0;
					int leadSpaces = 0;
					int daysInPrevMonth = 0;
					int prevMonth = 0;
					int prevYear = 0;
					int nextMonth = 0;
					int nextYear = 0;

					Log.d("Jennifer "+tag, "Month: " + mm + " " + "Year: " + yy );
					GregorianCalendar cal = new GregorianCalendar(yy, mm, currentDayOfMonth);

					// Days in Current Month
					daysInMonth = daysOfMonth[mm];
					int currentMonth = mm;
					if (currentMonth == 11)
						{
							prevMonth = 10;
							daysInPrevMonth = daysOfMonth[prevMonth];
							nextMonth = 0;
							prevYear = yy;
							nextYear = yy + 1;
						} else if (currentMonth == 0)
						{
							prevMonth = 11;
							prevYear = yy - 1;
							nextYear = yy;
							daysInPrevMonth = daysOfMonth[prevMonth];
							nextMonth = 1;
						} else
						{
							prevMonth = currentMonth - 1;
							nextMonth = currentMonth + 1;
							nextYear = yy;
							prevYear = yy;
							daysInPrevMonth = daysOfMonth[prevMonth];
						}

					// Compute how much to leave before before the first day of the
					// month.
					// getDay() returns 0 for Sunday.
					//Get the first day of the month
					TimeZone MyTimezone = TimeZone.getDefault();
					Calendar getFirstDay = new GregorianCalendar(MyTimezone);
					getFirstDay.set(yy, mm, 1, 0, 0, 0);
					int firstDay =getFirstDay.get(Calendar.DAY_OF_WEEK);
					//Log.d("Jennifer "+tag, "Calculated first day of the month: "+ getFirstDay.get(Calendar.DAY_OF_WEEK));
					
					trailingSpaces = getFirstDay.get(Calendar.DAY_OF_WEEK) - 1;
					
					//Log.d("Jennifer "+tag, "Trailing spaces(calendar day of the week): "+trailingSpaces );
					
					if (cal.isLeapYear(cal.get(Calendar.YEAR)) && mm == 1)
						{
							++daysInMonth;
						} 

					// Trailing Month days
					for (int i = 0; i < trailingSpaces; i++)
						{
							list.add(String.valueOf((daysInPrevMonth - trailingSpaces + 1) + i) + "-GREYED" + "-" + prevMonth + "-" + prevYear);
						}

					// Current Month Days
					for (int i = 1; i <= daysInMonth; i++)
						{
							list.add(String.valueOf(i) + "-MAIN" + "-" + mm + "-" + yy);
						}

					// Leading Month days
					for (int i = 0; i < list.size() % 7; i++)
						{
							//Log.d(tag, "NEXT MONTH:= " + months[nextMonth]);
							list.add(String.valueOf(i + 1) + "-GREYED" + "-" +nextMonth + "-" + nextYear);
						}
				}

			@Override
			public long getItemId(int position)
				{
					return position;
				}

			@Override
			public View getView(int position, View convertView, ViewGroup parent)
				{
		
					Log.d(tag, "getView ...");
					Log.d(tag, "position is: "+position);
					View row = convertView;
					if (row == null)
						{
							// ROW INFLATION
							Log.d(tag, "Starting XML Row Inflation ... ");
							LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);

							Log.d(tag, "Successfully completed XML Row Inflation!");
						}

					// Get a reference to the Day gridcell
					gridcell = (Button) row.findViewById(R.id.day_gridcell);
					gridcell.setOnClickListener(this);
					
					
					
					// ACCOUNT FOR SPACING

					Log.d(tag, "Current Day: " + currentDayOfMonth);
					String[] day_color = list.get(position).split("-");
					gridcell.setText(day_color[0]);
					
					gridcell.setTag(day_color[0] + "-" + day_color[2] + "-" + day_color[3]);

					if (day_color[1].equals("GREYED"))
						{
							gridcell.setTextColor(Color.parseColor("#999999"));
						}
					if (day_color[1].equals("MAIN"))
						{
							gridcell.setTextColor(Color.parseColor("#333333"));
						}
					
						Calendar cal=Calendar.getInstance();
						SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
						String monthName = month_date.format(cal.getTime());
					
						
					if (day_color[0].equals(currentDayOfMonth+"")&&  day_color[2].equals(monthName))
						{
							gridcell.setTextColor(Color.BLUE);
						}

					return row;
				}

			@Override
			public void onClick(View view)
				{
					Log.d(tag, "+++++----------------->In onclick" );
					String date_month_year = (String) view.getTag();
					Date calendarDate = getClickedCalendarDate(date_month_year);
					
					
					listAdapter = new ListAdapter(getApplicationContext(), R.id.list_item,fullRssFeed,calendarDate );
					listAdapter.notifyDataSetChanged();
					eventListView.setAdapter(listAdapter);
					
					if(selectedDay == null){
						Log.d(tag, "+++++----------------->selected day is null" );
						selectedDay = (Button) view;
						selectedDay.setBackgroundResource(R.drawable.calender_bg_purple);
					}
					else{
						Log.d(tag, "+++++----------------->selected day not null" );
						selectedDay.setBackgroundResource(R.drawable.calender_bg_grey);
						selectedDay = (Button) view;
						selectedDay.setBackgroundResource(R.drawable.calender_bg_purple);
					}
					Log.d(tag, "+++++----------------->out of onclick" );
					
				}
			
			private Date getClickedCalendarDate(String tag){
				String[] splitTag = tag.split("-");
				
				int cDate = Integer.parseInt(splitTag[0]);
				int cMonth = Integer.parseInt(splitTag[1]);
				int cYear = Integer.parseInt(splitTag[2]);
				Date calendarDate = new GregorianCalendar(cYear,cMonth,cDate).getTime();
				
				return calendarDate;
			}
		}

	
	
	

}
